/**
 * @file lv_100ask_demo_get_icon.c
 *
 */

/*********************
 *      INCLUDES
 *********************/




#include <stdio.h>
#include <time.h>
#include <sys/time.h>
#include <dirent.h>
#include "init_icon.h"
#include "../../libcurl_output/include/curl/curl.h"
#include "cJSON.h"
#include "../about/about.h"
#include "../file/file.h"
#include "../set_time/set_time.h"
#include "../wlan/set_wlan.h"
#include "../lan/set_lan.h"
#include "../weather/weather.h"
#include "../ashining_g01_dp6/ashining_g01_dp6.h"


#define ICON_PATH   ("./icon/")
#define BG_IMG_NAME ("bg.png")


#define MENU_TABLE_TIPS_PROMPT  (15)     // 菜单位置提示大小

#define ICON_SIZE           (64)
#define ICON_ROW_COUNT      (4)
#define ICON_COLUNM_COUNT   (3)
#define ICON_PAD_TOP        (40)
#define ICON_PAD_BOTTOM     (40)
#define ICON_PAD_LEFT       (115)
#define ICON_PAD_RIGHT      (115)

#define ICON_ROW_SPACE      (60)
#define ICON_COL_SPACE      (90)//((ICON_HOR_RES - (ICON_SIZE * ICON_COLUNM_COUNT)) / (ICON_COLUNM_COUNT - 1))
#define ICON_HOR_RES        (4 + (ICON_SIZE * ICON_COLUNM_COUNT) + (ICON_COL_SPACE * (ICON_COLUNM_COUNT - 1)))// 列间距
#define ICON_VER_RES        (4 + (ICON_SIZE * ICON_ROW_COUNT) + (ICON_ROW_SPACE * (ICON_ROW_COUNT - 1)))// 行间距

#define APPNAME_MAXLEN (32)
#define APPNUM_MAX (16)//最大支持16个app

static uint16_t g_tab_act = 1;  // 更新tabview的索引，用于返回桌面时保持原来的位置

static lv_obj_t * tv;
static lv_obj_t * calendar;
static lv_style_t style_text_muted;
static lv_style_t style_title;
static lv_style_t style_icon;
static lv_style_t style_bullet;
static const lv_font_t * font_large;
static const lv_font_t * font_normal;
static lv_obj_t * chart1;

static lv_chart_series_t * ser1;
lv_obj_t * greenHouseTba_label;
ResponseLonin responseLonin;
ResGetCommand resGetCommand;
char appName[APPNUM_MAX][APPNAME_MAXLEN] = {0};

static void calendar_event_cb(lv_event_t * e);
void loginToServer();

// 去掉最后的后缀名
static void strip_ext(char *fname)
{
    char *end = fname + strlen(fname);

    while (end > fname && *end != '.') {
        --end;
    }

    if (end > fname) {
        *end = '\0';
    }
}


// 替换给定字符串中所有出现的字符。
static void str_replace_all(char * str, char old_char, char new_char)
{
    int i = 0;

    /* Run till end of string */
    while(str[i] != '\0')
    {
        /* If occurrence of character is found */
        if(str[i] == old_char)
        {
            str[i] = new_char;
        }
        i++;
    }
}

static void event_handler(lv_event_t * e)
{
    lv_event_code_t code = lv_event_get_code(e);
    lv_obj_t * obj = lv_event_get_target(e);
    char * str_user_data = lv_event_get_user_data(e);
    LV_LOG_USER("str_user_data: %s", str_user_data);//str_user_data=app.Weather.png

    if(code == LV_EVENT_CLICKED) {

        if (0 == strncmp(str_user_data, "app.About.png", strlen("app.About.png"))){
            LV_LOG_USER("start about");
            about(lv_scr_act());
        }else if (0 == strncmp(str_user_data, "app.FileManager.png", strlen("app.FileManager.png"))){
            LV_LOG_USER("file manager");
            file(lv_scr_act());
        }else if (0 == strncmp(str_user_data, "app.SetTime.png", strlen("app.SetTime.png"))){
            LV_LOG_USER("set time");
            set_time(lv_scr_act());
        }else if (0 == strncmp(str_user_data, "app.WLAN.png", strlen("app.WLAN.png"))){
            LV_LOG_USER("set wlan");
            set_wlan(lv_scr_act());
        }else if (0 == strncmp(str_user_data, "app.LAN.png", strlen("app.LAN.png"))){
            LV_LOG_USER("set lan");
            set_lan(lv_scr_act());
        }else if (0 == strncmp(str_user_data, "app.Weather.png", strlen("app.Weather.png"))){
            LV_LOG_USER("weather");
            weather(lv_scr_act());
        }
        
    }
}


static void lv_timer_update_time(lv_timer_t * timer)
{
    lv_obj_t * label = timer->user_data;

    // 获取系统时间
    char buf[32];
    time_t rawtime;
    struct tm *info;
    time(&rawtime);
    info = localtime(&rawtime);

    lv_label_set_text_fmt(label, "  %02d-%02d-%02d   %02d:%02d", (info->tm_year + 2000 - 100), (info->tm_mon + 1), info->tm_mday, info->tm_hour, info->tm_min);
}

static void lcd_top_widgets(lv_obj_t * parent)
{
    static lv_style_t obj_layout_style;   // 容器的样式

    lv_style_init(&obj_layout_style);
    lv_style_set_pad_all(&obj_layout_style, 0);
    lv_style_set_bg_opa(&obj_layout_style, 0);
    lv_style_set_text_font(&obj_layout_style, &lv_font_montserrat_16);
    lv_style_set_border_opa(&obj_layout_style, 0);
    lv_style_set_radius(&obj_layout_style, 0);
    lv_style_set_text_color(&obj_layout_style, lv_color_hex(0xffffff));

    /* Layout Init */
    lv_obj_t * panel = lv_obj_create(parent);
    lv_obj_set_size(panel,  LV_PCT(100), 30);
    lv_obj_add_style(panel, &obj_layout_style, 0);
    lv_obj_align(panel, LV_ALIGN_TOP_MID, 0, 5);

    /* 右上角小图标 */
    lv_obj_t * panel_icon = lv_obj_create(panel);
    lv_obj_set_size(panel_icon,  200, 25);
    lv_obj_set_layout(panel_icon, LV_LAYOUT_FLEX);
    lv_obj_set_style_base_dir(panel_icon, LV_BASE_DIR_RTL, 0);
    lv_obj_set_flex_flow(panel_icon, LV_FLEX_FLOW_ROW);
    lv_obj_align(panel_icon, LV_ALIGN_RIGHT_MID, 0, 0);
    lv_obj_add_style(panel_icon, &obj_layout_style, 0);

    lv_obj_t * label = lv_label_create(panel_icon);
    lv_label_set_text(label,  " ");

    lv_obj_t * label_bat = lv_label_create(panel_icon);
    lv_label_set_text(label_bat,  LV_SYMBOL_BATTERY_EMPTY);

    lv_obj_t * label_batchar = lv_label_create(label_bat);
    lv_obj_set_style_text_font(label_batchar, &lv_font_montserrat_14, 0);
    lv_label_set_text(label_batchar,  LV_SYMBOL_CHARGE);
    lv_obj_center(label_batchar);


    lv_obj_t * label_wifi = lv_label_create(panel_icon);
    lv_label_set_text(label_wifi, LV_SYMBOL_WIFI);

    lv_obj_t * label_time = lv_label_create(panel);
    lv_label_set_text(label_time, "  ");
    lv_obj_align(label_time, LV_ALIGN_LEFT_MID, 0, 0);

    lv_timer_t * timer = lv_timer_create(lv_timer_update_time, 1000,  label_time);
}


static void clean_screen_obj(lv_obj_t * parent)
{
    uint32_t i;
    for(i = 0; i < lv_obj_get_child_cnt(parent); i++)
    {
        lv_obj_t * child = lv_obj_get_child(parent, i);
        if (child != lv_scr_act())
            lv_obj_del(child);  // lv_obj_clean
        /*Do something with child*/
    }
}


static void set_menu_table_tips(lv_obj_t * parent, int count)
{
    lv_obj_t * round[2];

    /* 主tab指示 */
    round[0] = lv_obj_create(parent);       // 主tab
    lv_obj_set_style_border_opa(round[0], 0, 0);
    lv_obj_set_size(round[0], MENU_TABLE_TIPS_PROMPT, MENU_TABLE_TIPS_PROMPT);
    lv_obj_align(round[0], LV_ALIGN_CENTER, -20, 260);

    round[1] = lv_obj_create(parent);       // 右tab
    lv_obj_set_style_border_opa(round[1], 0, 0);
    lv_obj_set_size(round[1], MENU_TABLE_TIPS_PROMPT, MENU_TABLE_TIPS_PROMPT);
    lv_obj_align(round[1], LV_ALIGN_CENTER, 20, 260);

    for(int i = 0; i < 2; i++)
    {
        if (i == count)
            lv_obj_set_style_bg_opa(round[i], LV_OPA_80, 0);
        else
            lv_obj_set_style_bg_opa(round[i], LV_OPA_30, 0);
    }

}

static void get_tab_act_index_event_handler(lv_event_t * e)
{
    lv_event_code_t code = lv_event_get_code(e);
    lv_obj_t * obj = lv_event_get_target(e);
    
    if(code == LV_EVENT_VALUE_CHANGED) {
        if (obj)
        {
            g_tab_act = lv_tabview_get_tab_act(obj);
        }
        else g_tab_act = 1;
    }
}


static void ta_event_cb(lv_event_t * e)
{
    lv_event_code_t code = lv_event_get_code(e);
    lv_obj_t * ta = lv_event_get_target(e);
    lv_obj_t * kb = lv_event_get_user_data(e);
    if(code == LV_EVENT_FOCUSED) {
        if(lv_indev_get_type(lv_indev_get_act()) != LV_INDEV_TYPE_KEYPAD) {
            lv_keyboard_set_textarea(kb, ta);
            lv_obj_set_style_max_height(kb, LV_HOR_RES * 2 / 3, 0);
            lv_obj_update_layout(tv);   /*Be sure the sizes are recalculated*/
            lv_obj_set_height(tv, LV_VER_RES - lv_obj_get_height(kb));
            lv_obj_clear_flag(kb, LV_OBJ_FLAG_HIDDEN);
            lv_obj_scroll_to_view_recursive(ta, LV_ANIM_OFF);
        }
    }
    else if(code == LV_EVENT_DEFOCUSED) {
        lv_keyboard_set_textarea(kb, NULL);
        lv_obj_set_height(tv, LV_VER_RES);
        lv_obj_add_flag(kb, LV_OBJ_FLAG_HIDDEN);
        lv_indev_reset(NULL, ta);

    }
    else if(code == LV_EVENT_READY || code == LV_EVENT_CANCEL) {
        lv_obj_set_height(tv, LV_VER_RES);
        lv_obj_add_flag(kb, LV_OBJ_FLAG_HIDDEN);
        lv_obj_clear_state(ta, LV_STATE_FOCUSED);
        lv_indev_reset(NULL, ta);   /*To forget the last clicked object to make it focusable again*/
    }
}

static void birthday_event_cb(lv_event_t * e)
{
    lv_event_code_t code = lv_event_get_code(e);
    lv_obj_t * ta = lv_event_get_target(e);

    if(code == LV_EVENT_FOCUSED) {
        if(lv_indev_get_type(lv_indev_get_act()) == LV_INDEV_TYPE_POINTER) {
            if(calendar == NULL) {
                lv_obj_add_flag(lv_layer_top(), LV_OBJ_FLAG_CLICKABLE);
                calendar = lv_calendar_create(lv_layer_top());
                lv_obj_set_style_bg_opa(lv_layer_top(), LV_OPA_50, 0);
                lv_obj_set_style_bg_color(lv_layer_top(), lv_palette_main(LV_PALETTE_GREY), 0);

                lv_obj_set_size(calendar, 300, 330);
                lv_calendar_set_showed_date(calendar, 1990, 01);
                lv_obj_align(calendar, LV_ALIGN_CENTER, 0, 30);
                lv_obj_add_event_cb(calendar, calendar_event_cb, LV_EVENT_ALL, ta);

                lv_calendar_header_dropdown_create(calendar);
            }
        }
    }
}

static void calendar_event_cb(lv_event_t * e)
{
    lv_event_code_t code = lv_event_get_code(e);
    lv_obj_t * ta = lv_event_get_user_data(e);
    lv_obj_t * obj = lv_event_get_current_target(e);
    if(code == LV_EVENT_VALUE_CHANGED) {
        lv_calendar_date_t d;
        lv_calendar_get_pressed_date(obj, &d);
        char buf[32];
        lv_snprintf(buf, sizeof(buf), "%02d.%02d.%d", d.day, d.month, d.year);
        lv_textarea_set_text(ta, buf);

        lv_obj_del(calendar);
        calendar = NULL;
        lv_obj_clear_flag(lv_layer_top(), LV_OBJ_FLAG_CLICKABLE);
        lv_obj_set_style_bg_opa(lv_layer_top(), LV_OPA_TRANSP, 0);
    }
}




static void chart_event_cb(lv_event_t * e)
{
    lv_event_code_t code = lv_event_get_code(e);
    lv_obj_t * obj = lv_event_get_target(e);

    if(code == LV_EVENT_PRESSED || code == LV_EVENT_RELEASED) {
        lv_obj_invalidate(obj); /*To make the value boxes visible*/
    }
    else if(code == LV_EVENT_DRAW_PART_BEGIN) {
        lv_obj_draw_part_dsc_t * dsc = lv_event_get_param(e);
        /*Set the markers' text*/
        if(dsc->part == LV_PART_TICKS && dsc->id == LV_CHART_AXIS_PRIMARY_X) {
            if(lv_chart_get_type(obj) == LV_CHART_TYPE_BAR) {
                const char * month[] = {"I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX", "X", "XI", "XII"};
                lv_snprintf(dsc->text, dsc->text_length, "%s", month[dsc->value]);
            } else {
                const char * month[] = {"Jan", "Febr", "March", "Apr", "May", "Jun", "July", "Aug", "Sept", "Oct", "Nov", "Dec"};
                lv_snprintf(dsc->text, dsc->text_length, "%s", month[dsc->value]);
            }
        }

        /*Add the faded area before the lines are drawn */
        else if(dsc->part == LV_PART_ITEMS) {
#if LV_DRAW_COMPLEX
            /*Add  a line mask that keeps the area below the line*/
            if(dsc->p1 && dsc->p2) {
                lv_draw_mask_line_param_t line_mask_param;
                lv_draw_mask_line_points_init(&line_mask_param, dsc->p1->x, dsc->p1->y, dsc->p2->x, dsc->p2->y, LV_DRAW_MASK_LINE_SIDE_BOTTOM);
                int16_t line_mask_id = lv_draw_mask_add(&line_mask_param, NULL);

                /*Add a fade effect: transparent bottom covering top*/
                lv_coord_t h = lv_obj_get_height(obj);
                lv_draw_mask_fade_param_t fade_mask_param;
                lv_draw_mask_fade_init(&fade_mask_param, &obj->coords, LV_OPA_COVER, obj->coords.y1 + h / 8, LV_OPA_TRANSP, obj->coords.y2);
                int16_t fade_mask_id = lv_draw_mask_add(&fade_mask_param, NULL);

                /*Draw a rectangle that will be affected by the mask*/
                lv_draw_rect_dsc_t draw_rect_dsc;
                lv_draw_rect_dsc_init(&draw_rect_dsc);
                draw_rect_dsc.bg_opa = LV_OPA_50;
                draw_rect_dsc.bg_color = dsc->line_dsc->color;

                lv_area_t obj_clip_area;
                _lv_area_intersect(&obj_clip_area, dsc->clip_area, &obj->coords);

                lv_area_t a;
                a.x1 = dsc->p1->x;
                a.x2 = dsc->p2->x - 1;
                a.y1 = LV_MIN(dsc->p1->y, dsc->p2->y);
                a.y2 = obj->coords.y2;
                lv_draw_rect(&a, &obj_clip_area, &draw_rect_dsc);

                /*Remove the masks*/
                lv_draw_mask_remove_id(line_mask_id);
                lv_draw_mask_remove_id(fade_mask_id);
            }
#endif


            const lv_chart_series_t * ser = dsc->sub_part_ptr;

            if(lv_chart_get_pressed_point(obj) == dsc->id) {
                if(lv_chart_get_type(obj) == LV_CHART_TYPE_LINE) {
                    dsc->rect_dsc->outline_color = lv_color_white();
                    dsc->rect_dsc->outline_width = 2;
                } else {
                    dsc->rect_dsc->shadow_color = ser->color;
                    dsc->rect_dsc->shadow_width = 15;
                    dsc->rect_dsc->shadow_spread = 0;
                }

                char buf[8];
                lv_snprintf(buf, sizeof(buf), "%d", dsc->value);

                lv_point_t text_size;
                lv_txt_get_size(&text_size, buf, font_normal, 0, 0, LV_COORD_MAX, LV_TEXT_FLAG_NONE);

                lv_area_t txt_area;
                if(lv_chart_get_type(obj) == LV_CHART_TYPE_BAR) {
                    txt_area.y2 = dsc->draw_area->y1 - LV_DPX(15);
                    txt_area.y1 = txt_area.y2 - text_size.y;
                    if(ser == lv_chart_get_series_next(obj, NULL)) {
                        txt_area.x1 = dsc->draw_area->x1 + lv_area_get_width(dsc->draw_area) / 2;
                        txt_area.x2 = txt_area.x1 + text_size.x;
                    } else {
                        txt_area.x2 = dsc->draw_area->x1 + lv_area_get_width(dsc->draw_area) / 2;
                        txt_area.x1 = txt_area.x2 - text_size.x;
                    }
                } else {
                    txt_area.x1 = dsc->draw_area->x1 + lv_area_get_width(dsc->draw_area) / 2 - text_size.x / 2;
                    txt_area.x2 = txt_area.x1 + text_size.x;
                    txt_area.y2 = dsc->draw_area->y1 - LV_DPX(15);
                    txt_area.y1 = txt_area.y2 - text_size.y;
                }

                lv_area_t bg_area;
                bg_area.x1 = txt_area.x1 - LV_DPX(8);
                bg_area.x2 = txt_area.x2 + LV_DPX(8);
                bg_area.y1 = txt_area.y1 - LV_DPX(8);
                bg_area.y2 = txt_area.y2 + LV_DPX(8);

                lv_draw_rect_dsc_t rect_dsc;
                lv_draw_rect_dsc_init(&rect_dsc);
                rect_dsc.bg_color = ser->color;
                rect_dsc.radius = LV_DPX(5);
                lv_draw_rect(&bg_area, dsc->clip_area, &rect_dsc);

                lv_draw_label_dsc_t label_dsc;
                lv_draw_label_dsc_init(&label_dsc);
                label_dsc.color = lv_color_white();
                label_dsc.font = font_normal;
                lv_draw_label(&txt_area, dsc->clip_area, &label_dsc, buf, NULL);
            } else {
                dsc->rect_dsc->outline_width = 0;
                dsc->rect_dsc->shadow_width = 0;
            }
        }
    }
}

static void eventHandlerLogin(lv_event_t * e)
{
    lv_event_code_t code = lv_event_get_code(e);

    if(code == LV_EVENT_CLICKED) {
        LV_LOG_USER("Clicked");
        loginToServer();
    }
    else if(code == LV_EVENT_VALUE_CHANGED) {
        LV_LOG_USER("Toggled");
    }
}

/**********************
 *   STATIC FUNCTIONS
 **********************/

static void profile_create(lv_obj_t * parent)
{
    lv_obj_t * panel1 = lv_obj_create(parent);
    lv_obj_set_height(panel1, LV_SIZE_CONTENT);


    lv_obj_t * avatar = lv_img_create(panel1);
    lv_img_set_src(avatar, "./icon/main.avatar.png");

    lv_obj_t * ID = lv_label_create(panel1);
    lv_label_set_text(ID, "ID:654654");
    lv_obj_add_style(ID, &style_title, 0);

    lv_obj_t * name = lv_label_create(panel1);
    lv_obj_set_style_text_font(name, &lv_font_siyuanheiti_normal_20, 0);
    lv_label_set_text(name, "姓名:张三");
    lv_obj_add_style(name, &style_title, 0);


    lv_obj_t * call_label = lv_label_create(panel1);
    lv_obj_set_style_text_font(call_label, &lv_font_siyuanheiti_normal_20, 0);
    lv_label_set_text(call_label, "手机号:16848698524");



    /*Create a keyboard*/
    lv_obj_t * kb = lv_keyboard_create(lv_scr_act());
    lv_obj_add_flag(kb, LV_OBJ_FLAG_HIDDEN);

    /*Create the second panel*/
    lv_obj_t * panel2 = lv_obj_create(parent);
    lv_obj_set_height(panel2, LV_SIZE_CONTENT);



    lv_obj_t * user_name_label = lv_label_create(panel2);
    lv_obj_set_style_text_font(user_name_label, &lv_font_siyuanheiti_normal_20, 0);
    lv_label_set_text(user_name_label, "手机号");
    lv_obj_add_style(user_name_label, &style_text_muted, 0);

    lv_obj_t * user_name = lv_textarea_create(panel2);
    lv_textarea_set_one_line(user_name, true);
    lv_obj_set_style_text_font(user_name, &lv_font_siyuanheiti_normal_20, 0);
    lv_textarea_set_placeholder_text(user_name, "你的手机号");
    lv_obj_add_event_cb(user_name, ta_event_cb, LV_EVENT_ALL, kb);

    lv_obj_t * password_label = lv_label_create(panel2);
    lv_obj_set_style_text_font(password_label, &lv_font_siyuanheiti_normal_20, 0);
    lv_label_set_text(password_label, "密码");
    lv_obj_add_style(password_label, &style_text_muted, 0);

    lv_obj_t * password = lv_textarea_create(panel2);
    lv_textarea_set_one_line(password, true);
    lv_textarea_set_password_mode(password, true);
    lv_obj_set_style_text_font(password, &lv_font_siyuanheiti_normal_20, 0);
    lv_textarea_set_placeholder_text(password, "最少6位");
    lv_obj_add_event_cb(password, ta_event_cb, LV_EVENT_ALL, kb);

    lv_obj_t * log_in_btn = lv_btn_create(panel2);
    lv_obj_set_size(log_in_btn, 200, LV_SIZE_CONTENT);
    lv_obj_add_event_cb(log_in_btn, eventHandlerLogin, LV_EVENT_ALL, NULL);
    lv_obj_t * label = lv_label_create(log_in_btn);
    lv_obj_set_style_text_font(label, &lv_font_siyuanheiti_normal_20, 0);
    lv_label_set_text(label, "登录");
    lv_obj_center(label);



    
    static lv_coord_t grid_main_col_dsc[] = {LV_GRID_FR(1), LV_GRID_FR(1), LV_GRID_TEMPLATE_LAST};
    static lv_coord_t grid_main_row_dsc[] = {LV_GRID_CONTENT, LV_GRID_CONTENT, LV_GRID_TEMPLATE_LAST};

    /*Create the top panel*/
    static lv_coord_t grid_1_col_dsc[] = {LV_GRID_FR(1), LV_GRID_FR(1), LV_GRID_TEMPLATE_LAST};
    static lv_coord_t grid_1_row_dsc[] = {LV_GRID_CONTENT, LV_GRID_CONTENT, LV_GRID_CONTENT, LV_GRID_CONTENT, LV_GRID_TEMPLATE_LAST};

    lv_obj_set_grid_dsc_array(parent, grid_main_col_dsc, grid_main_row_dsc);

    lv_obj_set_grid_cell(panel1, LV_GRID_ALIGN_STRETCH, 0, 1, LV_GRID_ALIGN_START, 0, 2);
    lv_obj_set_grid_dsc_array(panel1, grid_1_col_dsc, grid_1_row_dsc);
    lv_obj_set_grid_cell(avatar,    LV_GRID_ALIGN_CENTER, 0, 2, LV_GRID_ALIGN_CENTER, 0, 1);//头像
    lv_obj_set_grid_cell(ID,        LV_GRID_ALIGN_CENTER, 0, 2, LV_GRID_ALIGN_CENTER, 1, 1);//ID
    lv_obj_set_grid_cell(name,      LV_GRID_ALIGN_CENTER,  0, 2, LV_GRID_ALIGN_CENTER, 2, 1);//姓名
    lv_obj_set_grid_cell(call_label, LV_GRID_ALIGN_CENTER, 0, 2, LV_GRID_ALIGN_START, 3, 1);//电话号
    //lv_obj_set_grid_cell(log_out_btn, LV_GRID_ALIGN_STRETCH, 4, 1, LV_GRID_ALIGN_CENTER, 3, 2);
    //lv_obj_set_grid_cell(invite_btn, LV_GRID_ALIGN_STRETCH, 5, 1, LV_GRID_ALIGN_CENTER, 3, 2);

    static lv_coord_t grid_2_col_dsc[] = {LV_GRID_FR(1), LV_GRID_FR(1), LV_GRID_TEMPLATE_LAST};
    static lv_coord_t grid_2_row_dsc[] = {
            LV_GRID_CONTENT,  /*Box title*/
            30,               /*Boxes*/
            5,                /*Separator*/
            30,               /*Boxes*/
            LV_GRID_TEMPLATE_LAST
    };
    lv_obj_set_grid_cell(panel2, LV_GRID_ALIGN_STRETCH, 1, 1, LV_GRID_ALIGN_START, 0, 2);
    lv_obj_set_grid_dsc_array(panel2, grid_2_col_dsc, grid_2_row_dsc);
    lv_obj_set_grid_cell(user_name, LV_GRID_ALIGN_STRETCH, 0, 1, LV_GRID_ALIGN_CENTER, 1, 1);
    lv_obj_set_grid_cell(user_name_label, LV_GRID_ALIGN_START, 0, 1, LV_GRID_ALIGN_START, 0, 1);
    lv_obj_set_grid_cell(password, LV_GRID_ALIGN_STRETCH, 1, 1, LV_GRID_ALIGN_CENTER, 1, 1);
    lv_obj_set_grid_cell(password_label, LV_GRID_ALIGN_START, 1, 1, LV_GRID_ALIGN_START, 0, 1);
    lv_obj_set_grid_cell(log_in_btn, LV_GRID_ALIGN_CENTER, 0, 2, LV_GRID_ALIGN_CENTER, 3, 1);

}

static void analytics_create(lv_obj_t * parent)
{
    lv_obj_set_flex_flow(parent, LV_FLEX_FLOW_ROW_WRAP);

    static lv_coord_t grid_chart_row_dsc[] = {LV_GRID_CONTENT, LV_GRID_FR(1), 10, LV_GRID_TEMPLATE_LAST};
    static lv_coord_t grid_chart_col_dsc[] = {20, LV_GRID_FR(1), LV_GRID_TEMPLATE_LAST};

    lv_obj_t * chart1_cont = lv_obj_create(parent);
    lv_obj_set_flex_grow(chart1_cont, 1);
    lv_obj_set_grid_dsc_array(chart1_cont, grid_chart_col_dsc, grid_chart_row_dsc);

    lv_obj_set_height(chart1_cont, LV_PCT(100));
    lv_obj_set_style_max_height(chart1_cont, 280, 0);

    lv_obj_t * title = lv_label_create(chart1_cont);
    lv_obj_set_style_text_font(title, &lv_font_siyuanheiti_normal_20, 0);
    lv_label_set_text(title, "温度");
    lv_obj_add_style(title, &style_title, 0);
    lv_obj_set_grid_cell(title, LV_GRID_ALIGN_START, 0, 2, LV_GRID_ALIGN_START, 0, 1);

    chart1 = lv_chart_create(chart1_cont);
    lv_group_add_obj(lv_group_get_default(), chart1);
    lv_obj_add_flag(chart1, LV_OBJ_FLAG_SCROLL_ON_FOCUS);
    lv_obj_set_grid_cell(chart1, LV_GRID_ALIGN_STRETCH, 1, 1, LV_GRID_ALIGN_STRETCH, 1, 1);
    lv_chart_set_axis_tick(chart1, LV_CHART_AXIS_PRIMARY_Y, 0, 0, 5, 1, true, 80);
    lv_chart_set_axis_tick(chart1, LV_CHART_AXIS_PRIMARY_X, 0, 0, 12, 1, true, 50);
    lv_chart_set_div_line_count(chart1, 0, 12);
    lv_chart_set_point_count(chart1, 12);
    lv_obj_add_event_cb(chart1, chart_event_cb, LV_EVENT_ALL, NULL);


    lv_obj_set_style_border_side(chart1, LV_BORDER_SIDE_LEFT | LV_BORDER_SIDE_BOTTOM, 0);
    lv_obj_set_style_radius(chart1, 0, 0);

    ser1 = lv_chart_add_series(chart1, lv_theme_get_color_primary(chart1), LV_CHART_AXIS_PRIMARY_Y);
    lv_chart_set_next_value(chart1, ser1, lv_rand(10, 80));
    lv_chart_set_next_value(chart1, ser1, lv_rand(10, 80));
    lv_chart_set_next_value(chart1, ser1, lv_rand(10, 80));
    lv_chart_set_next_value(chart1, ser1, lv_rand(10, 80));
    lv_chart_set_next_value(chart1, ser1, lv_rand(10, 80));
    lv_chart_set_next_value(chart1, ser1, lv_rand(10, 80));
    lv_chart_set_next_value(chart1, ser1, lv_rand(10, 80));
    lv_chart_set_next_value(chart1, ser1, lv_rand(10, 80));
    lv_chart_set_next_value(chart1, ser1, lv_rand(10, 80));
    lv_chart_set_next_value(chart1, ser1, lv_rand(10, 80));
    lv_chart_set_next_value(chart1, ser1, lv_rand(10, 80));
    lv_chart_set_next_value(chart1, ser1, lv_rand(10, 80));
    lv_chart_set_next_value(chart1, ser1, lv_rand(10, 80));


    greenHouseTba_label = lv_label_create(parent);
    lv_obj_set_style_text_font(greenHouseTba_label, &lv_font_siyuanheiti_normal_20, 0);
    lv_label_set_text(greenHouseTba_label, "提示:");
    lv_obj_add_style(greenHouseTba_label, &style_title, 0);
    lv_obj_add_flag(greenHouseTba_label, LV_OBJ_FLAG_FLEX_IN_NEW_TRACK);
    lv_obj_set_flex_grow(greenHouseTba_label, 1);
    lv_obj_set_height(greenHouseTba_label, LV_PCT(100));
    lv_obj_set_style_max_height(greenHouseTba_label, 30, 0);
}

void tab_widgets(lv_obj_t *container)
{
    LV_LOG_USER("LV_HOR_RES=%d", LV_HOR_RES);
    lv_coord_t tab_h;
    
    tab_h = 70;
    font_large     =  &lv_font_montserrat_24;
    font_normal    =  &lv_font_montserrat_16;

    lv_obj_clear_flag(container, LV_OBJ_FLAG_SCROLLABLE);//禁用滚动

    lv_style_init(&style_text_muted);
    lv_style_set_text_opa(&style_text_muted, LV_OPA_50);

    lv_style_init(&style_title);
    lv_style_set_text_font(&style_title, font_large);

    lv_style_init(&style_icon);
    lv_style_set_text_color(&style_icon, lv_theme_get_color_primary(NULL));
    lv_style_set_text_font(&style_icon, font_large);

    lv_style_init(&style_bullet);
    lv_style_set_border_width(&style_bullet, 0);
    lv_style_set_radius(&style_bullet, LV_RADIUS_CIRCLE);

    tv = lv_tabview_create(container, LV_DIR_TOP, tab_h);
    lv_obj_set_style_text_font(tv, &lv_font_siyuanheiti_normal_20, 0);
    lv_obj_set_style_text_font(container, font_normal, 0);


    lv_obj_t * tab_btns = lv_tabview_get_tab_btns(tv);
    lv_obj_set_style_pad_left(tab_btns, LV_HOR_RES / 2, 0);
    lv_obj_t * logo = lv_img_create(tab_btns);
    lv_img_set_src(logo, "./icon/main.logo.png");
    lv_obj_align(logo, LV_ALIGN_LEFT_MID, -LV_HOR_RES / 2 + 0, 0);

    lv_obj_t * label = lv_label_create(tab_btns);
    lv_obj_add_style(label, &style_title, 0);
    lv_obj_set_style_text_font(label, &lv_font_siyuanheiti_normal_20, 0);
    lv_label_set_text(label, "绿色大棚");
    lv_obj_align_to(label, logo, LV_ALIGN_OUT_RIGHT_MID, 10, 0);


    lv_obj_t * t1 = lv_tabview_add_tab(tv, "用户");
    lv_obj_t * t2 = lv_tabview_add_tab(tv, "大棚");
    lv_obj_t * t3 = lv_tabview_add_tab(tv, "搜索");
    profile_create(t1);
    analytics_create(t2);
    //shop_create(t3);


}

//加小部件到 main tab
void addWidgetTomainTab(lv_obj_t * tab_main){
    lv_obj_t *container = lv_obj_create(tab_main);
    lv_obj_set_size(container, 480, 500);
    lv_obj_center(container);
    tab_widgets(container);
}

void jsonToStructLogin(char *text){
	cJSON *json;
	cJSON *cjsonItem;

	json=cJSON_Parse(text);
	if (!json) {
        printf("Error before: [%s]\n",cJSON_GetErrorPtr());
    }else{
		cjsonItem = cJSON_GetObjectItem(json, "ret");
        responseLonin.ret = cjsonItem->valueint;
        cjsonItem = cJSON_GetObjectItem(json, "message");
        lv_snprintf(responseLonin.message, sizeof(responseLonin.message), "%s", cjsonItem->valuestring);
		cJSON_Delete(json);
	}
}

size_t WriteCallback(void *contents, size_t size, size_t nmemb, void *userp) {
    size_t totalSize = size * nmemb;  // 计算总数据大小

    LV_LOG_USER("totalSize=%d", totalSize);
    char *buf = (char *)malloc(totalSize + 1);  // 动态分配内存，+1用于存放'\0'
    if (buf == NULL)
    {
        fprintf(stderr, "Memory allocation failed.\n");  // 内存分配失败
        return 0;
    }
    memcpy(buf, contents, totalSize);  // 拷贝数据到buf中
    buf[totalSize] = '\0';  // 添加字符串结束符
    printPrettyJSON(buf);
    jsonToStructLogin(buf);
    LV_LOG_USER("responseLonin: ret=%d, message=%s", responseLonin.ret, responseLonin.message);
    lv_label_set_text(greenHouseTba_label, "提示:登录成功");
    free(buf);  // 释放内存

    return totalSize;
}



void loginToServer()
{
    int i = 0;
    /*Use the user_data*/


    CURL *curl;
    CURLcode res;
    //char *url = "http://192.168.51.114:8080/iclock/pos_getdata\SN=48282260014&datatype=1";
    char *url = "http://49.235.141.38:8186/login?name=test&password=123456";
 
    curl_global_init(CURL_GLOBAL_DEFAULT);
    curl = curl_easy_init();
 
    if(curl) {
        curl_easy_setopt(curl, CURLOPT_URL, url);
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);
 
        res = curl_easy_perform(curl);
 
        if(res != CURLE_OK){
            fprintf(stderr, "curl_easy_perform() failed: %s\n", curl_easy_strerror(res));
        }
 
        curl_easy_cleanup(curl);
    }
 
    curl_global_cleanup();

}

void my_timer(lv_timer_t * timer)
{
    uint32_t * user_data = timer->user_data;
    //LV_LOG_USER("my_timer called with user data: %d\n", *user_data);
    //LV_LOG_USER("my_timer is run");
    getCommandFromServer();
}

void jsonToStructGetCommand(char *text){
	cJSON *json;
	cJSON *cjsonItem;

	json=cJSON_Parse(text);
	if (!json) {
        printf("Error before: [%s]\n",cJSON_GetErrorPtr());
    }else{
		cjsonItem = cJSON_GetObjectItem(json, "ret");
        resGetCommand.ret = cjsonItem->valueint;
        cjsonItem = cJSON_GetObjectItem(json, "message");
        lv_snprintf(resGetCommand.message, sizeof(resGetCommand.message), "%s", cjsonItem->valuestring);
        if(resGetCommand.ret == 0){
            cjsonItem = cJSON_GetObjectItem(json, "command");
            lv_snprintf(resGetCommand.command, sizeof(resGetCommand.command), "%s", cjsonItem->valuestring);
            cjsonItem = cJSON_GetObjectItem(json, "status");
            if (cjsonItem->type == cJSON_True){
                resGetCommand.status = true;
            }else{
                resGetCommand.status = false;
            }

        }

		cJSON_Delete(json);
	}
}

size_t CallbackGetCommand(void *contents, size_t size, size_t nmemb, void *userp) {
    size_t totalSize = size * nmemb;  // 计算总数据大小
    char tempString[64] = {0};

    //LV_LOG_USER("totalSize=%d", totalSize);
    char *buf = (char *)malloc(totalSize + 1);  // 动态分配内存，+1用于存放'\0'
    if (buf == NULL)
    {
        fprintf(stderr, "Memory allocation failed.\n");  // 内存分配失败
        return 0;
    }
    memcpy(buf, contents, totalSize);  // 拷贝数据到buf中
    buf[totalSize] = '\0';  // 添加字符串结束符
    jsonToStructGetCommand(buf);
    if (resGetCommand.ret == 0){
        printPrettyJSON(buf);
        
        LV_LOG_USER("resGetCommand: ret=%d, message=%s, command=%s, status=%d", resGetCommand.ret, resGetCommand.message, resGetCommand.command, resGetCommand.status);

        lv_snprintf(tempString, sizeof(tempString), "提示:取命令成功,命令=%s, status=%d", resGetCommand.command, resGetCommand.status);
        lv_label_set_text(greenHouseTba_label, tempString);
    }
    
    
    free(buf);  // 释放内存

    return totalSize;
}


void getCommandFromServer(){
    int i = 0;
    /*Use the user_data*/

    CURL *curl;
    CURLcode res;
    char *url = "http://49.235.141.38:8186/machine/getCommand?machineID=123&token=654";
 
    curl_global_init(CURL_GLOBAL_DEFAULT);
    curl = curl_easy_init();
 
    if(curl) {
        curl_easy_setopt(curl, CURLOPT_URL, url);
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, CallbackGetCommand);
 
        res = curl_easy_perform(curl);
 
        if(res != CURLE_OK){
            fprintf(stderr, "curl_easy_perform() failed: %s\n", curl_easy_strerror(res));
        }
 
        curl_easy_cleanup(curl);
    }
 
    curl_global_cleanup();

}

/* print text to pretty JSON string! */
void printPrettyJSON(char *text)
{
	char *out;cJSON *json;
	
	json=cJSON_Parse(text);
	if (!json) {printf("Error before: [%s]\n",cJSON_GetErrorPtr());}
	else
	{
		out=cJSON_Print(json);
		cJSON_Delete(json);
		printf("%s\n",out);
		free(out);
	}
}


//
void lv_100ask_demo_init_icon(void)
{
    DIR *dr;
    struct dirent *de;              // Pointer for directory entry
    char bg_path_name[128];         // 存放桌面背景路径的缓冲区
    char icon_path_name[128];       // 存放APP图标路径的缓冲区
    int appCount = 0;

    lv_obj_t * img_gb;              // 桌面背景
    lv_obj_t * img_icon;            // APP图标

    lv_obj_t * label_icon_name;     // 展示在图标下方的名称
    lv_obj_t * tabview_desktop;     // tab总页面




    lv_obj_t * tab_main;            // 中间的tab页面
    lv_obj_t * tab_right;           // 右边的tab页面


    lv_obj_t * icon_cont_right;     // 中间图标区域面板

    static lv_style_t style_tabview_desktop;    // 容器的样式
  	static lv_style_t cont_style;               // 中间图标区域，容器的样式
	static lv_style_t icon_style;               // 中间图标区域，容器中的图标的样式


    if (lv_obj_get_child(lv_scr_act(), 0))
    lv_obj_del(lv_obj_get_child(lv_scr_act(), 0));
    lv_obj_t * screen = lv_obj_create(NULL);
    lv_scr_load(screen);



    lv_style_init(&style_tabview_desktop);
    lv_style_set_bg_opa(&style_tabview_desktop, 0);


	/* 设置容器的样式 */
	lv_style_init(&cont_style);
    lv_style_set_bg_opa(&cont_style, 0);
    lv_style_set_border_opa(&cont_style, 0);
    lv_style_set_pad_column(&cont_style, ICON_COL_SPACE);
    lv_style_set_pad_row(&cont_style, ICON_ROW_SPACE);
    lv_style_set_pad_all(&cont_style, 0);
    lv_style_set_layout(&cont_style, LV_LAYOUT_FLEX);
    lv_style_set_base_dir(&cont_style, LV_BASE_DIR_LTR);
    lv_style_set_flex_flow(&cont_style, LV_FLEX_FLOW_ROW_WRAP);

	/* 容器中的图标的样式 */
	lv_style_init(&icon_style);
    lv_style_set_text_opa(&icon_style, 0);
    lv_style_set_text_font(&icon_style,  &lv_font_montserrat_8);



    // 桌面背景
    img_gb = lv_img_create(lv_scr_act());
    lv_snprintf(bg_path_name, sizeof(bg_path_name), "%s%s", ICON_PATH, BG_IMG_NAME); 
    lv_img_set_src(img_gb, bg_path_name);

    /* 屏幕顶部状态栏区域 */
    lcd_top_widgets(lv_scr_act());

    /*Create a Tab view object*/
    tabview_desktop = lv_tabview_create(lv_scr_act(), LV_DIR_TOP, 0);
    lv_obj_add_style(tabview_desktop, &style_tabview_desktop, 0);
    lv_obj_add_event_cb(tabview_desktop, get_tab_act_index_event_handler, LV_EVENT_VALUE_CHANGED, NULL);
    /*Add 2 tabs (the tabs are page (lv_page) and can be scrolled*/
    tab_main  = lv_tabview_add_tab(tabview_desktop, "main_desktop");
    tab_right = lv_tabview_add_tab(tabview_desktop, "right_desktop");
    lv_tabview_set_act(tabview_desktop, g_tab_act, LV_ANIM_OFF);

	/* main tab面板 */  
    addWidgetTomainTab(tab_main);

    icon_cont_right = lv_obj_create(tab_right);
    lv_obj_set_size(icon_cont_right, ICON_HOR_RES, ICON_VER_RES);
    lv_obj_center(icon_cont_right);
    lv_obj_add_style(icon_cont_right, &cont_style, 0);



    // TAB位置提示
    set_menu_table_tips(tab_main, 0);
    set_menu_table_tips(tab_right, 1);

    // opendir() returns a pointer of DIR type. 
    //DIR *dr = opendir("assets/icon");
    dr = opendir(ICON_PATH);
  
    if (dr == NULL)  // opendir returns NULL if couldn't open directory
    {
        printf("Could not open current directory!\n");
        return 0;
    }
    
    appCount = 0;
    //取 app 图标并显示到 桌面
    while ((de = readdir(dr)) != NULL)
    {
        //只存取 .png 扩展名的文件名 
        if((strcmp(de->d_name,".") == 0)  ||\
           (strcmp(de->d_name,"..") == 0) ||\
           (strcmp((de->d_name + (strlen(de->d_name) - 4)) , ".png") != 0))
        {
            continue;
        }
        LV_LOG_USER("de->d_name=%s", de->d_name);
        // 图标名要以 app. 开头
        if(0 != strncmp(de->d_name, "app.", strlen("app."))){
            continue;
        }
        appCount++;
        strncpy(&appName[appCount - 1][0], de->d_name, APPNAME_MAXLEN);
        

        // 获取图片的： 路径+名称
        memset(icon_path_name, 0, sizeof(icon_path_name));
        lv_snprintf(icon_path_name, sizeof(icon_path_name), "%s%s", ICON_PATH, de->d_name); 

        // 摆放APP到右tab
        img_icon = lv_img_create(icon_cont_right);
        label_icon_name = lv_label_create(tab_right);    // 显示在图标下方的app名称
  


        
        // 图标
        LV_LOG_USER("icon_path_name=%s", icon_path_name);
        lv_img_set_src(img_icon, icon_path_name);
        lv_obj_add_flag(img_icon, LV_OBJ_FLAG_CLICKABLE);
        lv_obj_add_style(img_icon, &icon_style, 0);
        lv_obj_add_event_cb(img_icon, event_handler, LV_EVENT_CLICKED, &appName[appCount - 1][0]);


        // 显示在图标下方的app名称
        lv_obj_set_style_text_font(label_icon_name, &lv_font_montserrat_14, 0);
        lv_obj_set_style_text_color(label_icon_name, lv_color_hex(0xffffff), 0);
        lv_obj_set_style_text_align(label_icon_name, LV_TEXT_ALIGN_CENTER, 0);
        lv_obj_set_width(label_icon_name, ICON_SIZE + 20);
        strip_ext(de->d_name);  // 去掉最后的后缀名 .png
        char *icon_name = strrchr(de->d_name, '.') + 1;
        LV_LOG_USER("icon_name=%s", icon_name);
        if(strcmp(icon_name, "LAN") == 0){
            lv_obj_set_style_text_font(label_icon_name, &lv_font_siyuanheiti_normal_20, 0);
            lv_label_set_text(label_icon_name, "有线网");
        }else if(strcmp(icon_name, "About") == 0){
            lv_obj_set_style_text_font(label_icon_name, &lv_font_siyuanheiti_normal_20, 0);
            lv_label_set_text(label_icon_name, "关于系统");
        }else if(strcmp(icon_name, "FileManager") == 0){
            lv_obj_set_style_text_font(label_icon_name, &lv_font_siyuanheiti_normal_20, 0);
            lv_label_set_text(label_icon_name, "文件浏览");
        }else if(strcmp(icon_name, "SetTime") == 0){
            lv_obj_set_style_text_font(label_icon_name, &lv_font_siyuanheiti_normal_20, 0);
            lv_label_set_text(label_icon_name, "设置时间");
        }else if(strcmp(icon_name, "Weather") == 0){
            lv_obj_set_style_text_font(label_icon_name, &lv_font_siyuanheiti_normal_20, 0);
            lv_label_set_text(label_icon_name, "天气");
        }
        else{
            lv_label_set_text(label_icon_name, icon_name);
        }
        
        lv_obj_align_to(label_icon_name, img_icon, LV_ALIGN_OUT_BOTTOM_MID, 0, 5);
        lv_obj_move_foreground(label_icon_name); // 防止被桌面背景图覆盖，将其移到前台           
        //printf("%s\n", de->d_name);
    }
    //lv_obj_move_background(img_gb);  // 将背景移动到后台
    closedir(dr);

    //定时器，网络通信
    //static uint32_t user_data = 10;
    //lv_timer_t * timer = lv_timer_create(my_timer, 3000,  &user_data);
    //lv_timer_set_repeat_count(timer, -1);//运行次数，设置为“-1”为无限重复
    

    //创建线程，泽耀模块G01-DP6通信
    //createNrf24l01Thread();

    return 0;
}




